<template>
  <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
    <el-form-item label="名称" prop="name" required>
      <el-input v-model="formItem.name" placeholder="请输入名称" />
    </el-form-item>
    <el-form-item label="编码" prop="code" required>
      <el-input v-model="formItem.code" placeholder="请输入编码" />
    </el-form-item>
    <el-form-item label="分类" prop="type" required>
      <el-select v-model="formItem.type" placeholder="请选择权限分类">
        <el-option
          v-for="item in permissionTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
import { create, update, detail } from '@neu/auth-ui/api/permission'
const permissionTypes = [
  {
    value: 'menu',
    label: '菜单'
  },
  {
    value: 'action',
    label: '按钮'
  }
]

// 定义一个表单原始项
const formItem = {
  name: '',
  code: '',
  type: ''
}
export default {
  name: 'PermissionsEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '标识不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择权限类型', trigger: 'change' }
        ]
      },
      permissionTypes: permissionTypes
    }
  },
  computed: {
    edited() {
      return this.id !== -1
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function(newVal, oldVal) {
      if (newVal > -1) {
        this.fetch()
      }
    }
  },
  created() {
    // 表单组件放在diaolog中，首次打开时，监控不到id的变化。所以需要在created中调用一次
    if (this.id > -1) {
      this.fetch()
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            name: response.data.name,
            code: response.data.code,
            type: response.data.type
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.edited
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
